<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    class Heap {
      constructor() {
        this.heap = [];
      }

      push(value) {
        this.heap.push(value);
        this.bubbleUp(this.heap.length - 1);
      }

      bubbleUp(index) {
        while (index > 0) {
          let parentIndex = Math.floor((index - 1) / 2);
          if (this.heap[parentIndex] > this.heap[index]) {
            [this.heap[parentIndex], this.heap[index]] = [this.heap[index], this.heap[parentIndex]];
            index = parentIndex;
          } else {
            break;
          }
        }
      }

      pop() {
        let minValue = this.heap[0];
        let lastIndex = this.heap.length - 1;
        this.heap[0] = this.heap[lastIndex];
        this.heap.pop();
        this.bubbleDown(0);
        return minValue;
      }

      bubbleDown(index) {
        while (index < this.heap.length) {
          let leftIndex = index * 2 + 1;
          let rightIndex = index * 2 + 2;
          let smallestIndex = index;
          if (leftIndex < this.heap.length && this.heap[leftIndex] < this.heap[smallestIndex]) {
            smallestIndex = leftIndex;
          }
          if (rightIndex < this.heap.length && this.heap[rightIndex] < this.heap[smallestIndex]) {
            smallestIndex = rightIndex;
          }
          if (smallestIndex !== index) {
            [this.heap[index], this.heap[smallestIndex]] = [this.heap[smallestIndex], this.heap[index]];
            index = smallestIndex;
          } else {
            break;
          }
        }
      }
    }

    // 使用堆进行排序
    let heap = new Heap();
    let arr = [6, 8, 10, 1, 2, 9, 7];
    arr.forEach(item => heap.push(item));
    let result = [];
    while (heap.heap.length > 0) {
      result.push(heap.pop());
    }
    console.log(result); // 输出[1, 2, 6, 7, 8, 9, 10]

  </script>
</body>

</html>